//
//  TF1to16ChatAreaCell.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/5/9.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit
import SDWebImage

class TF1to16ChatAreaCell: UITableViewCell {

    @objc public let avatar = UIImageView()
    @objc public var viewWidth:CGFloat = 0
    @objc public var viewHight:CGFloat = 0
    @objc public var model:TF1to16LiveChatData?
    {
        didSet
        {
         if(model != nil)
         {
             self.modelUI(model!)
            
         }
            
        }
    }
    let theme = UIImageView()
    var image1 = UIImage()
    let time = UILabel()
    let name = UILabel()
    
    let content = TF_StoyCopyTextView()
    //用户身份
    let roleLabel = UILabel()

    //聊天
    //--------------------------------------------------
    //奖励
    //提示的图片
    let awardViePromptButton = TFAwardPromptButton()
    let manager = SDWebImageManager()
    
    let fullScreen = UIView()
    let imageButton = TFZoomButton()
 
   
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
   
        self.contentView.addSubview(self.avatar)
        
        //其它人的名字
//        self.name.backgroundColor = .clear
        self.name.textColor = UIColor.white
        self.name.numberOfLines = 0
        self.contentView.addSubview(self.name)
        self.name.isHidden = true;
        
        //时间
//        self.name.backgroundColor = .clear
        self.time.textColor = UIColor.white
        self.time.numberOfLines = 0
        self.contentView.addSubview(self.time)
        self.time.isHidden = true
        
        //聊天内容
        self.content.backgroundColor = UIColor.clear
        self.content.textColor = UIColor.white
        self.content.isHidden = true
        self.content.textContainer.lineFragmentPadding = 0
        self.content.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.content.font =  UIFont.PingFang(size: 14)
        self.content.isScrollEnabled = false
        self.contentView.addSubview(self.content)
        
 
        self.contentView.addSubview(self.roleLabel)
        self.roleLabel.backgroundColor = UIColor(red: 242/255.0, green: 84/255.0, blue: 66/255.0, alpha: 1)
      
        //提示
        self.awardViePromptButton.backgroundColor =  UIColor(red: 49/255.0 , green: 52/255.0, blue: 57/255.0, alpha: 1)
        self.contentView.addSubview(self.awardViePromptButton)
        self.awardViePromptButton.isHidden = true
        self.awardViePromptButton.setTitleColor(UIColor(red: 255/255.0 , green: 182/255.0, blue: 86/255.0, alpha: 1), for: .normal)
      
        
        //表情图片
        self.theme.backgroundColor = UIColor.clear
        self.theme.contentMode = .scaleAspectFit;
        self.contentView.addSubview(self.theme)
        self.theme.isUserInteractionEnabled = true
        
        self.theme.addSubview(self.imageButton)
        self.imageButton.isHidden = true
        self.imageButton.addTarget(self, action: #selector(self.imageButtonClick), for: .touchUpInside)
       
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let awardViePromptButtonH:CGFloat = 40
        let awardViePromptButtonW:CGFloat = 211
        let awardViePromptButtonX:CGFloat = (self.frame.size.width-awardViePromptButtonW)/2;
        let awardViePromptButtonY:CGFloat = self.frame.size.height-awardViePromptButtonH
          self.awardViePromptButton.frame = CGRect(x: awardViePromptButtonX, y: awardViePromptButtonY, width: awardViePromptButtonW, height: awardViePromptButtonH)
          self.awardViePromptButton.titleLabel!.font =
        UIFont.PingFang(size: 14)
          
          self.awardViePromptButton.layer.cornerRadius = 20
    }
    
    @objc func modelUI(_ model:TF1to16LiveChatData)
    {
        self.roleLabel.isHidden = true
     //奖励
     if (model.isAward) {
         self.imageButton.isHidden = true
         self.avatar.isHidden = true
         self.time.isHidden = true
         self.name.isHidden = true
         self.content.isHidden = true
         self.awardViePromptButton.isHidden = false
         self.awardViePromptButton.lab1.text = model.nickname
       
     }else{
         self.avatar.isHidden = true;

        
         var spadminstring:NSMutableAttributedString = NSMutableAttributedString.init(string: "")
         var roleStr:String = ""
         
         if (model.role == .roleSpadmin) {
             self.roleLabel.isHidden = false;
             
             roleStr = "主播"

         } else if (model.role == .roleAdmin) {
             self.roleLabel.isHidden = false
             
             roleStr = "助理"
         }
         

         let size1: CGSize = roleStr.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 10) as Any])
       
         
         
         let roleLabelWidth:CGFloat = size1.width + 6
      // 10 是5左  5右距离
         let spadminWidth = 6+28+roleLabelWidth
     
         spadminstring = NSMutableAttributedString.getAttributed(string: roleStr, font: UIFont.PingFang(size: 10), foregroundColor: UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1))
         
         self.avatar.sd_setImage(with: NSURL.init(string: model.avatar) as URL?)
        
         self.awardViePromptButton.isHidden = true
         self.name.isHidden = false
         self.content.isHidden = false
         self.time.isHidden = false
    
         //其它人的名字
         var  nickname:NSString = model.nickname as NSString
         
         if (model.role == .roleAdmin) {
             
             nickname = "助理" as NSString
         }
         
         var timeW:CGFloat = 48
         
         //时间
         let currentDateStr = TalkfunSharedTools.getTimestamp(mStr: model.time as NSString) as String
    
         let othersNameString = NSMutableAttributedString.getAttributed(string: currentDateStr, font: UIFont.PingFang(size: 14), foregroundColor: UIColor.init(hexString: "#20C667"))
             
             self.time.attributedText = othersNameString
           
            
         let attrsSize: CGSize = currentDateStr.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 14)])
         
        
             timeW = attrsSize.width
       
         
         if (nickname.length > 6 ) {
             nickname =  nickname.substring(with:NSRange(location: 0, length: 6)) as NSString
             nickname =  (nickname as String) + "..." as NSString
            
         }
         
         let size: CGSize = nickname.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 14)])
         
         var  nameW:CGFloat = size.width
         if (size.width > self.viewWidth - timeW - 15 - 15 - spadminWidth) {
             
             nameW = self.viewWidth - timeW - 15 - 15 - spadminWidth
         }
         
         let nameStr = NSMutableAttributedString.getAttributed(string: model.nickname , font: UIFont.PingFang(size: 14), foregroundColor: UIColor.init(hexString: "#20C667"))
         
       
         self.name.attributedText = nameStr
         self.name.lineBreakMode = .byCharWrapping
         
         //是我自己,在右边
         if (model.isMe){
             
             let avatarW:CGFloat = 0
             let avatarH:CGFloat = 32
             let avatarX:CGFloat = self.viewWidth-32-15
             let avatarY:CGFloat = 20.5
               self.avatar.frame = CGRect(x: avatarX, y: avatarY, width: avatarW, height: avatarH)
             
             let nameH:CGFloat = 18.5
             let othersNameY:CGFloat = 15
             let timeH:CGFloat = nameH
             
             let nameX:CGFloat = self.viewWidth - nameW - 11
             
             let timeY:CGFloat = othersNameY;
             
            
             let timeX:CGFloat = nameX - nameW - timeW
             

             self.name.frame = CGRect(x: nameX, y: othersNameY, width: nameW, height: nameH)
            
             
             self.time.frame = CGRect(x: timeX, y: timeY, width: timeW, height: timeH)
          
              self.roleLabel.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
         }else{
             
             let avatarW:CGFloat = 0
             let avatarH:CGFloat = 32
             let avatarX:CGFloat = 15
             let avatarY:CGFloat = 20.5
               self.avatar.frame = CGRect(x: avatarX, y: avatarY, width: avatarW, height: avatarH)
            
             let othersNameX:CGFloat = 11
             let othersNameY:CGFloat = 15
             let nameH:CGFloat = 18.5
             
             self.name.frame = CGRect(x: othersNameX, y: othersNameY, width: nameW, height: nameH)
         
             
             
             self.roleLabel.layer.masksToBounds = true
             self.roleLabel.frame = CGRect(x: self.name.frame.maxX+6, y: othersNameY, width: roleLabelWidth, height: nameH)
            
             self.roleLabel.layer.cornerRadius = 2
       
              self.roleLabel.attributedText = spadminstring
             self.roleLabel.textAlignment = .center
              self.roleLabel.textColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
             
             
             if (spadminWidth>0) {
                 let timeH = nameH
                 let timeX = self.roleLabel.frame.maxX+15
                 let timeY = othersNameY
                self.time.frame = CGRect(x: timeX, y: timeY, width: timeW, height: timeH)
             
             }else{
                 let timeH = nameH;
                 let timeX = self.name.frame.maxX+15
                 let timeY = othersNameY
                 self.time.frame = CGRect(x: timeX, y: timeY, width: timeW, height: timeH)
                 
             }
     
         }
         
         self.avatar.layer.masksToBounds = true;
        // 圆角半径
         self.avatar.layer.cornerRadius =  self.avatar.frame.size.width/2;
         
         let contentAttrStr = TalkfunSharedTools.getAttributedText(model.msg, fontSize: UIFont.PingFang(size: 14), foregroundColor: UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1))

         let replyList = model.replyList as NSArray
         
         let reversedArray:NSArray = replyList.reverseObjectEnumerator().allObjects as NSArray
         for i in 0..<reversedArray.count

         {
             let reply = reversedArray[i] as! TFChatReply
             
             var aa:String = ""
             
                 aa = aa + "@"
                 aa = aa+(reply.nickname as String)
             
                 aa = aa+(" " as String)

             
                 
             let attrsSize:CGSize = aa.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 14)])
             
                 let aaL = UILabel()
             
                 aaL.frame = CGRect(x: 0, y: 0, width: attrsSize.width+2, height: attrsSize.height+2)
                 aaL.text = aa
                 aaL.font = UIFont.PingFang(size: 14)
             if reply.isMe {
                 aaL.textColor = UIColor(red: 86/255.0, green: 172/255.0, blue: 245/255.0, alpha: 1)
                 aaL.backgroundColor = UIColor(red: 86/255.0, green: 172/255.0, blue: 245/255.0, alpha: 1)
             }else{
                 aaL.backgroundColor = UIColor.clear
             }
              
                 aaL.clipsToBounds = true
                 aaL.layer.cornerRadius = 4
                 aaL.textAlignment = .center

                 //调用方法，转化成Image
             
            let image = TalkfunSharedTools.imageWithUIView(aaL)
         
             
             //创建Image的富文本格式
             let attach = NSTextAttachment()
             attach.bounds = CGRect(x: 0, y: -(aaL.bounds.size.height/4), width: aaL.bounds.size.width, height: aaL.bounds.size.height)
        //这个-2.5是为了调整下标签跟文字的位置
             attach.image = image;
             //添加到富文本对象里
     
            let  imageStr = NSAttributedString.init(attachment: attach)
         
         //加入文字前面
             contentAttrStr.insert(imageStr, at: 0)
             
             
         }
         self.content.addHyperlink(font: UIFont.PingFang(size: 14), attributedText: contentAttrStr)
         self.content.attributedText = contentAttrStr
         self.content.isEditable = false
      
         let contentWidth:CGFloat = self.viewWidth-42
         
         let size11 = TalkfunSharedTools.getSizeLabel(labelString: contentAttrStr, labelWidth: contentWidth, labelfont: UIFont.PingFang(size: 14))
         
         let emoticonHight:CGFloat = self.viewHight-(36.5+12+24)
         //自己
         if (model.isMe)
         {
             self.content.frame = CGRect(x: 33, y: 36.5, width: contentWidth, height: size11.height)
        
             
             self.name.textAlignment = .right
             
             //如果是两行了,是左对齐
             
             let Wrap = self.sizeLabelToFit(contentAttrStr, width: contentWidth, fontSize: UIFont.PingFang(size: 14))
             if (Wrap ) {
                 self.content.textAlignment =  .left
             }else{
                 self.content.textAlignment =  .right
             }
             
           
          self.theme.frame = CGRect(x: 55, y: 36.5+12, width: contentWidth, height: emoticonHight)
           
         }else{
          self.theme.frame = CGRect(x: 55, y: 36.5+12, width: contentWidth, height: emoticonHight)
             
             self.content.frame = CGRect(x:8 , y: 36.5+12, width: contentWidth, height: size11.height)
             
             self.name.textAlignment = .left
             self.content.textAlignment =  .left
             
         }
         
         //TODO:是聊天表情
            if (model.imageURL.count>0) {
                  self.content.isHidden = true

                self.manager.loadImage(with: NSURL.init(string: model.imageURL) as URL?) { receivedSize, expectedSize, targetURL in
                    
                } completed: { image, data, error, cacheType, finished, imageURL in
                
                           
                           if (image != nil) {
                               
                               self.image1 = image!
                            
                               self.imageButton.imageView!.contentMode = .scaleAspectFill
                               self.imageButton.setImage(image, for: .normal)
                              
                                self.imageButton.isHidden = false
                               if (image!.size.width<self.theme.frame.size.width) {
                                self.imageButton.isUserInteractionEnabled = false
                                self.imageButton.zoom.isHidden = true
                                   self.imageButton.frame = CGRect(x: 0, y: 0, width: image!.size.width, height: image!.size.height)
                           
                               }else{
                                self.imageButton.isUserInteractionEnabled = true
                                 self.imageButton.frame = CGRect(x: 0, y: 0, width: self.theme.frame.size.width, height: self.theme.frame.size.height)
                           
                               }
                           }else{
                              self.imageButton.isHidden = true;
                               self.content.attributedText = TalkfunSharedTools.getAttributedText("加载失败", fontSize: UIFont.PingFang(size: 14), foregroundColor: UIColor.white)
                            
                             
                               self.content.isHidden = false
                           }
                          
                           
                }
                       
                
               
                 self.theme.isHidden = false
            }else{
                self.theme.isHidden = true
                
                self.content.isHidden = false
                
            }
     }
    
    }

    //全屏
    @objc func imageButtonClick()
    {
        
        let window = TalkfunSharedTools.keyWindow()
            
        
            
            self.fullScreen.backgroundColor = UIColor.clear
            self.fullScreen.frame = window.frame
                
            window.addSubview(self.fullScreen)
                

            let browseView = UIImageView.init(frame: self.fullScreen.frame)
            browseView.backgroundColor = UIColor(red: 21/255.0, green: 34/255.0, blue: 54/255.0, alpha: 0.95)
            browseView.contentMode = .scaleAspectFit
            browseView.image = self.image1

            self.fullScreen.addSubview(browseView)
                    
            let imageView = UIButton()
            imageView.contentMode = .scaleAspectFit
            imageView.setImage(UIImage.init(named: "HTLive.bundle/suoxiao"), for: .normal)
               
            imageView.frame = CGRect(x: self.fullScreen.frame.size.width - 50 - 25, y: self.fullScreen.frame.size.height - 50 - 10, width: 50, height: 50)
            
            imageView.backgroundColor = UIColor(red:  29/255.0, green: 56/255.0, blue: 83/255.0, alpha: 0.6)
          
            
            imageView.layer.cornerRadius = 25
            imageView.addTarget(self, action: #selector(self.imageViewClick), for: .touchUpInside)
               
            self.fullScreen.addSubview(imageView)
        
         
       

    }
    //缩小
    @objc func imageViewClick()
    {
        self.fullScreen.removeFromSuperview()
    }
    
    @objc func sizeLabelToFit(_ aString:NSAttributedString,width:CGFloat,fontSize:UIFont)->Bool
    {
        let tempLabel = UILabel.init(frame: CGRect(x: 0, y: 0, width: width, height: 0))
        tempLabel.font = fontSize
        tempLabel.attributedText = aString
        tempLabel.sizeToFit()
      
        let size = tempLabel.frame.size
        
        if (size.width>width) {
            return true
        }
    
        return  false;
    }
}
